#/usr/bin/env python
# -*- coding: utf8 -*-
# title       :
# description :
# author      :'ShenMeng'

import yaml
import maya.cmds as cmds
import maya.mel as mel
import os
import sys

class Smhuds(object):
    """
    import smhuds.core
    sm_huds = smhuds.core.Smhuds(config='huds_config.yml')
    sm_huds.show()
    """
    def __init__(self, config):
        self._config = config
        self._builtin_huds = []
        self._config_huds = []
        self._block_size = None
        self._data_font_size = None
        self._label_font_size = None
        self._expression_name = "verHudsExpression"
        self._parse_config()
        
    @staticmethod
    def parse_yaml_file(file_path):
        data = None
        with open(str(file_path)) as f:
            data = yaml.load(f)
        return data
        
    @staticmethod
    def get_handle(name):
        try:
            del sys.modules[name]
        except:pass
        handle = __import__(name)
        return handle
        
    def _set_size(self):
        all_huds = cmds.headsUpDisplay(lh=1)
        for _huds in all_huds:
            cmds.headsUpDisplay(_huds, e=1, 
                                bs = self._block_size if self._block_size else 'small', 
                                lfs = self._label_font_size if self._label_font_size else 'small', 
                                dfs = self._data_font_size if self._data_font_size else 'small')
        
    def _invoke_hook(self, name):
        try:
            del sys.modules[name]
        except:pass
        return 'import {name};{name}.{main}'.format(name = name, main="main()")
        #return handle.main()
    
    def _parse_config(self):
        root_path = os.path.dirname(os.path.dirname(__file__))
        config_file = os.path.join(root_path, "config", self._config)
        hooks_path = os.path.join(root_path, "hooks")
        if os.path.isfile(config_file):
            data = self.parse_yaml_file(config_file)
            self._config_huds = data.get("sections", [])
            self._builtin_huds = data.get("builtin", [])
            self._block_size = data.get("blockSize", None)
            self._label_font_size = data.get("labelFontSize", None)
            self._data_font_size = data.get("dataFontSize", None)
            sys.path.append(hooks_path)

    def _create_expression(self):
        if not self._config_huds:
            return
        str_parts = []
        for _huds, data in self._config_huds.iteritems():
            if data.get('refresh'):
                str_parts.append("cmds.headsUpDisplay('{}', refresh=1)".format(_huds))
        if str_parts:
            str_cmd = ';'.join(str_parts)
            cmds.expression(name=self._expression_name,
                            string="python(\"import maya.cmds as mc;{}\")".format(str_cmd),
                            object="", 
                            alwaysEvaluate=1, 
                            unitConversion="all")
                        
    def get_expression_name(self):
        return self._expression_name

    def delete_expression(self):
        all_expression = cmds.ls(type='expression')
        if not all_expression:
            return
        for _expression in all_expression:
            if self._expression_name in _expression:
                cmds.delete(_expression)
            
    def clear(self):
        self.delete_expression()
        self.set_builtin_huds(0)
        all_huds = cmds.headsUpDisplay(lh=1)
        for _huds in all_huds:
            cmds.headsUpDisplay(_huds, e=1, vis=0)
        if not self._config_huds:
            return
        for _huds in self._config_huds:
            if cmds.headsUpDisplay(_huds, ex=1):
                cmds.headsUpDisplay(_huds, rem=1)
                
    def set_builtin_huds(self, value):
        if not self._builtin_huds:
            return
        for _huds in self._builtin_huds:
            mel.eval("{}({})".format(_huds, value))
            
    def get_huds_str(self, data):
        str_parts = []
        for key, value in data.iteritems():
            if key == 'refresh':
                continue
            if isinstance(value, str):
                str_parts.append('{}="{}"'.format(key, value))
            else:
                str_parts.append('{}={}'.format(key, value))
        if str_parts:
            return ','.join(str_parts)

    def show(self):
        self.clear()
        if not self._config_huds:
            return
        for _huds, data in self._config_huds.iteritems():
            _data = data.copy()
            _block = cmds.headsUpDisplay(nextFreeBlock=_data['section'])
            command_name = _data['command']
            com_value = self._invoke_hook(command_name)
            _data['command'] = com_value
            _huds_str = self.get_huds_str(_data)
            eval("""cmds.headsUpDisplay("{}", block={}, {})""".format(_huds, _block, _huds_str))
        self.set_builtin_huds(1)
        self._create_expression()
        self._set_size()
    


